package com.pansoft.openplanet.activity;

import android.content.Context;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SwitchCompat;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.http.EFHttpRequest;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.view.CircleImageView;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * 资产列表
 * Created by yqs on 2018/06/05
 */

public class AssetListActivity extends TCBaseActivity implements View.OnClickListener {
    public static final String TAG = "AssetListActivity";
//    private RelativeLayout toplayout;
//    private ImageView ivBack;
//    private LinearLayout llSearch;
//    private TextView tvSerach;
//    private TextView tvManager;
    private RecyclerView recycleview;
    private List<AssetListBean> dataList = new ArrayList<>();
    private AssetListAdapter adapter;
    private ArrayList<AssetListBean> assetList = new ArrayList<>();
    private String accountAddress;

    private int mode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_asset_list);
        mode = getIntent().getExtras().getInt("mode");
        if (getIntent().getExtras() != null && getIntent().getExtras().containsKey("asset_list")) {
            assetList.addAll((ArrayList<AssetListBean>) getIntent().getExtras().getSerializable("asset_list"));
        }
        initView();
        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    private void initView() {
//        toplayout = (RelativeLayout) findViewById(R.id.toplayout);
//        ivBack = (ImageView) findViewById(R.id.iv_back);
//        llSearch = (LinearLayout) findViewById(R.id.ll_search);
//        tvSerach = (TextView) findViewById(R.id.tv_serach);
//        tvManager = (TextView) findViewById(R.id.tv_manager);
//        ivBack.setOnClickListener(this);

        recycleview = (RecyclerView) findViewById(R.id.recycleview);
        recycleview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AssetListAdapter(this, R.layout.open_planet_item_assetlist_item, dataList);
        recycleview.setAdapter(adapter);


        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.open_planet_asset_etc_wallet_assets);
                findViewById(R.id.iv_back).setOnClickListener(this);

    }

    /**
     * 请求所有代币列表
     */
    private void initData() {
        accountAddress = getIntent().getStringExtra("accountAddress");
        //请求该链上的所有代币数据
        HashMap<String, String> params = new HashMap<>();

            params.put("chainID",mode+"");//链编号ETC传2 pwr传4

//        params.put("userAddress", EnvironmentVariable.getProperty("tc_ethAddress"));
        params.put("userAddress", accountAddress);

        TCRequestUtil.getCommonRequest(TAG, "chain/getAllTokenByChain", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                JSONArray jsonArray = jsonObject.optJSONArray("AllTokenByChain");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject walletObject = jsonArray.getJSONObject(i);
                                        AssetListBean assetListBean = new AssetListBean.Builder()
                                                .address(walletObject.optString("tokenAddress"))
                                                .icon(walletObject.optString("tokenIcon"))
                                                .name(walletObject.optString("tokenName"))
                                                .secondName(walletObject.optString("tokenFullName"))
                                                .balance(walletObject.optString("balance"))
                                                .id(walletObject.optString("tokenID"))
                                                .blockChainID(walletObject.optString("blockChainID"))
                                                .tokenDecimals(walletObject.optInt("tokenDecimals"))
                                                .isSelected(walletObject.optBoolean("isSelected"))
                                                .build();
                                        dataList.add(assetListBean);
                                    }
                                    //请求完后比较，设置选中状态
                                    compareDataList();
                                }
                                adapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        ToastUtils.showShort(R.string.common_text_network_error_please_again);
                    }
                });
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            EFHttpRequest.cancelRequest(TAG);
            finish();
        }

    }

    /**
     * 比较请求到的代币列表，和传入的关注的代币列表，已关注的设置selected状态
     */
    private void compareDataList() {
        if (assetList.size() > 0) {
            for (AssetListBean assetListBean : assetList) {
                for (int i = 0; i < dataList.size(); i++) {
                    if (assetListBean.equals(dataList.get(i))) {
                        dataList.get(i).setSelected(true);
                    }
                }
            }
        }
    }

    public class AssetListAdapter extends CommonAdapter<AssetListBean> {
        private List<AssetListBean> datas;

        public AssetListAdapter(Context context, int layoutId, List<AssetListBean> datas) {
            super(context, layoutId, datas);
            this.datas = datas;
        }

        @Override
        protected void convert(ViewHolder holder, AssetListBean assetListBean, final int position) {
            CircleImageView ivIamge;
            TextView tvName;
            TextView tvName2;
            TextView tvAddress;
            final SwitchCompat switchButton;

            ivIamge = (CircleImageView) holder.getView(R.id.iv_iamge);
            tvName = (TextView) holder.getView(R.id.tv_name);
            tvName2 = (TextView) holder.getView(R.id.tv_name2);
            tvAddress = (TextView) holder.getView(R.id.tv_address);
            switchButton = (SwitchCompat) holder.getView(R.id.switch_button);

            assetListBean = datas.get(position);
            LXGlideImageLoader.getInstance().displayImage(mContext, ivIamge, assetListBean.getIcon());
            tvName.setText(assetListBean.getName());
            tvName2.setText(assetListBean.getSecondName());
            //处理地址显示
            String address = assetListBean.getAddress();
            if (address.length() > 20) {
                String formatAddress = address.replace(address.substring(6, address.length() - 4), "****");
                tvAddress.setText(formatAddress);
            } else {
                tvAddress.setText("");
            }
            if (assetListBean.isSelected()) {
                switchButton.setChecked(true);
            } else {
                switchButton.setChecked(false);
            }

            final AssetListBean finalAssetListBean = assetListBean;
            switchButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateTokenFollow(finalAssetListBean.getId(), finalAssetListBean.isSelected(), position);
                }
            });
        }
    }

    /**
     * 更新资产关注状态
     * 0 取消关注 1 关注
     * @param follow 是否已经关注，已经关注，则取消关注，传0；未关注，则关注，传1
     */
    private void updateTokenFollow(String tokenID, final boolean follow, final int position) {
        HashMap<String, String> params = new HashMap<>();
        params.put("chainID",mode+"");//链编号ETC传2
//        params.put("userAddress", EnvironmentVariable.getProperty("tc_ethAddress"));
        params.put("userAddress", accountAddress);

        params.put("tokenID", tokenID);
        params.put("type", follow ? "0" : "1");
        TCRequestUtil.getCommonRequest(TAG, "chain/updateUserToken", params,
                new TCRequestUtil.TCRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.optString("result").equals("success")) {
                                dataList.get(position).setSelected(!follow);
                                adapter.notifyItemChanged(position);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
    }

    //    private void initDataList() {
//        dataList = new ArrayList<>();
//        AssetListBean assetListBean0 = new AssetListBean();
//        assetListBean0.setSelected(false);
//        assetListBean0.setValue("0");
//        assetListBean0.setName(getString(R.string.ETH_NAME));
//        assetListBean0.setSecondName(getString(R.string.ETH_SUB_NAME));
//        assetListBean0.setIcon(getString(R.string.ETH_IMG_URL));
//        final String address = EnvironmentVariable.getProperty("tc_ethAddress");
//        if (address.length() > 20) {
//            String formatAddress = address.replace(address.substring(6, address.length() - 4), "****");
//            assetListBean0.setAddress(formatAddress);
//        } else {
//            assetListBean0.setAddress("");
//        }
//
//        dataList.add(assetListBean0);
//
//        AssetListBean assetListBean = new AssetListBean();
//        assetListBean.setSelected(false);
//        assetListBean.setValue("0");
//        assetListBean.setName(getString(R.string.EOS_NAME));
//        assetListBean.setSecondName(getString(R.string.EOS_SUB_NAME));
//        assetListBean.setIcon(getString(R.string.EOS_IMG_URL));
//        assetListBean.setAddress("0x0d5d****0001");
//        dataList.add(assetListBean);
//
//        AssetListBean assetListBean19 = new AssetListBean();
//        assetListBean19.setSelected(false);
//        assetListBean19.setValue("0");
//        assetListBean19.setName(getString(R.string.TRX_NAME));
//        assetListBean19.setSecondName(getString(R.string.TRX_SUB_NAME));
//        assetListBean19.setIcon(getString(R.string.TRX_IMG_URL));
//        assetListBean19.setAddress("0x0d5d****89f5");
//        dataList.add(assetListBean19);
//
//        AssetListBean assetListBean1 = new AssetListBean();
//        assetListBean1.setSelected(false);
//        assetListBean1.setValue("0");
//        assetListBean1.setName(getString(R.string.VEN_NAME));
//        assetListBean1.setSecondName(getString(R.string.VEN_SUB_NAME));
//        assetListBean1.setIcon(getString(R.string.VEN_IMG_URL));
//        assetListBean1.setAddress("0x0d5d****4561");
//        dataList.add(assetListBean1);
//
//        AssetListBean assetListBean2 = new AssetListBean();
//        assetListBean2.setSelected(false);
//        assetListBean2.setValue("0");
//        assetListBean2.setName(getString(R.string.BNB_NAME));
//        assetListBean2.setSecondName(getString(R.string.BNB_SUB_NAME));
//        assetListBean2.setIcon(getString(R.string.BNB_IMG_URL));
//        assetListBean2.setAddress("0x0d5d****dfs4");
//        dataList.add(assetListBean2);
//
//        AssetListBean assetListBean3 = new AssetListBean();
//        assetListBean3.setSelected(false);
//        assetListBean3.setValue("0");
//        assetListBean3.setName(getString(R.string.OMG_NAME));
//        assetListBean3.setSecondName(getString(R.string.OMG_SUB_NAME));
//        assetListBean3.setIcon(getString(R.string.OMG_IMG_URL));
//        assetListBean3.setAddress("0x0d5d****ad46");
//        dataList.add(assetListBean3);
//
//        AssetListBean assetListBean4 = new AssetListBean();
//        assetListBean4.setSelected(false);
//        assetListBean4.setValue("0");
//        assetListBean4.setName(getString(R.string.ICX_NAME));
//        assetListBean4.setSecondName(getString(R.string.ICX_SUB_NAME));
//        assetListBean4.setIcon(getString(R.string.ICX_IMG_URL));
//        assetListBean4.setAddress("0x0d5d****a02f");
//        dataList.add(assetListBean4);
//
//        AssetListBean assetListBean5 = new AssetListBean();
//        assetListBean5.setSelected(false);
//        assetListBean5.setValue("0");
//        assetListBean5.setName(getString(R.string.ZIL_NAME));
//        assetListBean5.setSecondName(getString(R.string.ZIL_SUB_NAME));
//        assetListBean5.setIcon(getString(R.string.ZIL_IMG_URL));
//        assetListBean5.setAddress("0x0d5d****4r76");
//        dataList.add(assetListBean5);
//
//        AssetListBean assetListBean6 = new AssetListBean();
//        assetListBean6.setSelected(false);
//        assetListBean6.setValue("0");
//        assetListBean6.setName(getString(R.string.AE_NAME));
//        assetListBean6.setSecondName(getString(R.string.AE_SUB_NAME));
//        assetListBean6.setIcon(getString(R.string.AE_IMG_URL));
//        assetListBean6.setAddress("0x0d5d****98i0");
//        dataList.add(assetListBean6);
//
//        AssetListBean assetListBean7 = new AssetListBean();
//        assetListBean7.setSelected(false);
//        assetListBean7.setValue("0");
//        assetListBean7.setName(getString(R.string.ZRX_NAME));
//        assetListBean7.setSecondName(getString(R.string.ZRX_SUB_NAME));
//        assetListBean7.setIcon(getString(R.string.ZRX_IMG_URL));
//        assetListBean7.setAddress("0x0d5d****j767");
//        dataList.add(assetListBean7);
//
//        AssetListBean assetListBean8 = new AssetListBean();
//        assetListBean8.setSelected(false);
//        assetListBean8.setValue("0");
//        assetListBean8.setName(getString(R.string.BTM_NAME));
//        assetListBean8.setSecondName(getString(R.string.BTM_SUB_NAME));
//        assetListBean8.setIcon(getString(R.string.BTM_IMG_URL));
//        assetListBean8.setAddress("0x0d5d****32w3");
//        dataList.add(assetListBean8);
//
//        AssetListBean assetListBean9 = new AssetListBean();
//        assetListBean9.setSelected(false);
//        assetListBean9.setValue("0");
//        assetListBean9.setName(getString(R.string.RHOC_NAME));
//        assetListBean9.setSecondName(getString(R.string.RHOC_SUB_NAME));
//        assetListBean9.setIcon(getString(R.string.RHOC_IMG_URL));
//        assetListBean9.setAddress("0x0d5d****5546");
//        dataList.add(assetListBean9);
//
//        AssetListBean assetListBean10 = new AssetListBean();
//        assetListBean10.setSelected(false);
//        assetListBean10.setValue("0");
//        assetListBean10.setName(getString(R.string.MKR_NAME));
//        assetListBean10.setSecondName(getString(R.string.MKR_SUB_NAME));
//        assetListBean10.setIcon(getString(R.string.MKR_IMG_URL));
//        assetListBean10.setAddress("0x0d5d****7y88");
//        dataList.add(assetListBean10);
//
//        AssetListBean assetListBean11 = new AssetListBean();
//        assetListBean11.setSelected(false);
//        assetListBean11.setValue("0");
//        assetListBean11.setName(getString(R.string.GNT_NAME));
//        assetListBean11.setSecondName(getString(R.string.GNT_SUB_NAME));
//        assetListBean11.setIcon(getString(R.string.GNT_IMG_URL));
//        assetListBean11.setAddress("0x0d5d****8e7e");
//        dataList.add(assetListBean11);
//
//        AssetListBean assetListBean12 = new AssetListBean();
//        assetListBean12.setSelected(false);
//        assetListBean12.setValue("0");
//        assetListBean12.setName(getString(R.string.PPT_NAME));
//        assetListBean12.setSecondName(getString(R.string.PPT_SUB_NAME));
//        assetListBean12.setIcon(getString(R.string.PPT_IMG_URL));
//        assetListBean12.setAddress("0x0d5d****k887");
//        dataList.add(assetListBean12);
//
//        AssetListBean assetListBean13 = new AssetListBean();
//        assetListBean13.setSelected(false);
//        assetListBean13.setValue("0");
//        assetListBean13.setName(getString(R.string.REP_NAME));
//        assetListBean13.setSecondName(getString(R.string.REP_SUB_NAME));
//        assetListBean13.setIcon(getString(R.string.REP_IMG_URL));
//        assetListBean13.setAddress("0x0d5d****90u7");
//        dataList.add(assetListBean13);
//
//        AssetListBean assetListBean14 = new AssetListBean();
//        assetListBean14.setSelected(false);
//        assetListBean14.setValue("0");
//        assetListBean14.setName(getString(R.string.WTC_NAME));
//        assetListBean14.setSecondName(getString(R.string.WTC_SUB_NAME));
//        assetListBean14.setIcon(getString(R.string.WTC_IMG_URL));
//        assetListBean14.setAddress("0x0d5d****37t7");
//        dataList.add(assetListBean14);
//
//        AssetListBean assetListBean15 = new AssetListBean();
//        assetListBean15.setSelected(false);
//        assetListBean15.setValue("0");
//        assetListBean15.setName(getString(R.string.IOST_NAME));
//        assetListBean15.setSecondName(getString(R.string.IOST_SUB_NAME));
//        assetListBean15.setIcon(getString(R.string.IOST_IMG_URL));
//        assetListBean15.setAddress("0x0d5d****2j65");
//        dataList.add(assetListBean15);
//
//        AssetListBean assetListBean16 = new AssetListBean();
//        assetListBean16.setSelected(false);
//        assetListBean16.setValue("0");
//        assetListBean16.setName(getString(R.string.SNT_NAME));
//        assetListBean16.setSecondName(getString(R.string.SNT_SUB_NAME));
//        assetListBean16.setIcon(getString(R.string.SNT_IMG_URL));
//        assetListBean16.setAddress("0x0d5d****1h12");
//        dataList.add(assetListBean16);
//
//        AssetListBean assetListBean17 = new AssetListBean();
//        assetListBean17.setSelected(false);
//        assetListBean17.setValue("0");
//        assetListBean17.setName(getString(R.string.NAS_NAME));
//        assetListBean17.setSecondName(getString(R.string.NAS_SUB_NAME));
//        assetListBean17.setIcon(getString(R.string.NAS_IMG_URL));
//        assetListBean17.setAddress("0x0d5d****u76e");
//        dataList.add(assetListBean17);
//
//        AssetListBean assetListBean18 = new AssetListBean();
//        assetListBean18.setSelected(false);
//        assetListBean18.setValue("0");
//        assetListBean18.setName(getString(R.string.AION_NAME));
//        assetListBean18.setSecondName(getString(R.string.AION_SUB_NAME));
//        assetListBean18.setIcon(getString(R.string.AION_IMG_URL));
//        assetListBean18.setAddress("0x0d5d****6et5");
//        dataList.add(assetListBean18);

//    }


    //    @Override
//    public void onBackPressed() {
//        Intent intent = new Intent();
//        getSelectedList();
//        intent.putExtra("result_asset_list", assetList);
//        setResult(RESULT_OK, intent);
//        finish();
//    }

//    private void getSelectedList() {
//        assetList.clear();
//        for (AssetListBean assetListBean : dataList) {
//            if (assetListBean.isSelected()) {
//                assetList.add(assetListBean);
//            }
//        }
//    }
}